<template>
  <span class="confirm-button-wrapper" @click.stop="handleWrapperClick">
    <template v-if="$slots.default">
      <span
        class="confirm-custom"
        :class="{ 'is-confirming': isConfirming }"
        :style="isConfirming ? confirmStyle : {}"
        @click.stop="handleButtonClick"
      >
        <template v-if="!isConfirming">
          <slot />
        </template>
        <template v-else>
          <el-icon><select-icon /></el-icon>
          <span>{{ confirmText }}</span>
        </template>
      </span>
    </template>
    <template v-else>
      <el-button
        ref="buttonRef"
        v-bind="$attrs"
        :type="isConfirming ? 'danger' : buttonType"
        :loading="loading"
        @click="handleButtonClick"
      >
        <el-icon><select-icon /></el-icon>
        {{ buttonText }}
      </el-button>
    </template>
  </span>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { Select as SelectIcon } from '@element-plus/icons-vue';

interface Props {
  text?: string;
  confirmText?: string;
  type?: 'primary' | 'success' | 'warning' | 'danger' | 'info';
  loading?: boolean;
  confirmTimeout?: number; // 确认状态超时时间（毫秒）
}

const props = withDefaults(defineProps<Props>(), {
  text: '确认',
  confirmText: '确认吗？',
  type: 'primary',
  loading: false,
  confirmTimeout: 3000 // 默认3秒后自动恢复
});

const emit = defineEmits<{
  confirm: [];
  click: [];
}>();

const isConfirming = ref(false);
const buttonRef = ref<HTMLElement>();
let confirmTimer: NodeJS.Timeout | null = null;

const buttonType = computed(() => (isConfirming.value ? 'danger' : props.type));

const buttonText = computed(() => (isConfirming.value ? props.confirmText : props.text));

const confirmStyle = {
  color: '#fff',
  background: '#f56c6c',
  borderRadius: '4px',
  padding: '2px 8px',
  cursor: 'pointer',
  transition: 'all 0.2s',
  userSelect: 'none'
};

// 处理按钮点击
const handleButtonClick = (event: Event) => {
  event.stopPropagation();

  if (isConfirming.value) {
    emit('confirm');
    resetConfirmState();
  } else {
    isConfirming.value = true;
    emit('click');
    startConfirmTimer();
  }
};

// 处理包装器点击（点击其他位置恢复）
const handleWrapperClick = (event: Event) => {
  if (isConfirming.value && event.target !== buttonRef.value) {
    resetConfirmState();
  }
};

// 开始确认计时器
const startConfirmTimer = () => {
  if (confirmTimer) {
    clearTimeout(confirmTimer);
  }
  confirmTimer = setTimeout(() => {
    resetConfirmState();
  }, props.confirmTimeout);
};

// 重置确认状态
const resetConfirmState = () => {
  isConfirming.value = false;
  if (confirmTimer) {
    clearTimeout(confirmTimer);
    confirmTimer = null;
  }
};

// 监听全局点击事件
const handleGlobalClick = (event: Event) => {
  if (isConfirming.value && !$elContains(event.target)) {
    resetConfirmState();
  }
};

// 判断点击是否在组件内
function $elContains(target: EventTarget | null) {
  const wrapper = buttonRef.value?.parentElement as HTMLElement | null;
  return wrapper && target instanceof Node && wrapper.contains(target);
}

onMounted(() => {
  document.addEventListener('click', handleGlobalClick);
});

onUnmounted(() => {
  document.removeEventListener('click', handleGlobalClick);
  if (confirmTimer) {
    clearTimeout(confirmTimer);
  }
});
</script>

<style lang="scss" scoped>
.confirm-button-wrapper {
  display: inline-block;
}
.confirm-custom {
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  transition: all 0.2s;
  user-select: none;
  &.is-confirming {
    color: #fff;
    background: #f56c6c;
    border-radius: 4px;
    padding: 2px 8px;
  }
}
</style>
